<?php


namespace App\Http\Services;

use App\Exceptions\BusinessException;
use App\Models\Dept;
use Exception;
use Illuminate\Support\Facades\DB;

class DeptService extends BaseService
{

    public function all(){
        $result = Dept::orderBy('sort','asc')->orderBy('id','desc')->get();
        return $result->transform(function($item){
            return [
                'id'=>$item->id,
                'name'=>$item->name,
                'value'=>$item->value
            ];
        });
    }

    public function tree(){
        $departments = Dept::where('status',1)->orderBy('sort','asc')->get()->toArray();

        $dept = $this->buildTree($departments);

        return $dept;
    }


    public function optionTree(){
        $departments = Dept::orderBy('sort','asc')->get()->toArray();
        $packDept = [];
        foreach ($departments as  $key => $item){
            $packDept[$key]['label'] = $item['name'];
            $packDept[$key]['value'] = $item['id'];
            $packDept[$key]['parent_id'] = $item['parent_id'];
        }

        $dept = $this->buildTree($packDept,0,'value');

        return $dept;
    }

    private function buildTree(array $elements, $parentId = 0,$pk='id')
    {
        $branch = [];
        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = $this->buildTree($elements, $element[$pk],$pk);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }

        return $branch;
    }


    public function list($params=[])
    {
        $model = Dept::whereNull('deleted_at');
        if(isset($params['name'])){
            $model->where('name','like','%'.$params['name'].'%');
        }
        $list = $model->orderBy('sort','asc')->orderBy('id','desc')->paginate();
        return $list;
    }

    public function store($params=[],$id=0)
    {

        $dept = null;
        if($id>0) {
            $dept = Dept::where('id', $id)->first();
            if (empty($dept)) {
                throw new BusinessException('未查询到数据');
            }
            $repeat = Dept::where('id', '<>', $id)->where(function($q) use ($params){
                $q->where('parent_id', $params['parentId']);
                $q->where('name',$params['name']);
            })->first();
            $repeat2 = Dept::where('id', '<>', $id)->where(function($q) use ($params){
                $q->where('code',$params['code']);
            })->first();
        }else{
            $repeat = Dept::where(function($q) use ($params){
                $q->where('parent_id', $params['parentId']);
                $q->where('name',$params['name']);
            })->first();
            $repeat2 = Dept::where(function($q) use ($params){
                $q->where('code',$params['code']);
            })->first();
        }

        if ($repeat) {
            throw new BusinessException('同级部门名称重复');
        }
        if ($repeat2) {
            throw new BusinessException('部门编码重复');
        }

        $add = [];
        $add["parent_id"]=$params['parentId'];
        $add["name"]= $params['name'];
        $add["code"]= $params['code'];
        $add["sort"]= $params['sort'] ?? 0;
        $add["status"]= $params['status'] ?? 1;


        DB::beginTransaction();
        if(empty($dept)){
            $addResult = Dept::create($add);
            if($addResult === false){
                DB::rollBack();
            }
        }else{
            $updateResult = $dept->update($add);
            if($updateResult === false){
                DB::rollBack();
            }
        }
        DB::commit();

        return true;
    }

    public function show($id)
    {
        $result = Dept::where('id',$id)->first();
        if(empty($result)){
            return [];
        }
        $result->parentId = $result->parent_id;
        return $result;
    }
    /**
     * delete
     */
    public function destroy($id)
    {
        $dept = Dept::find($id);
        if(empty($dept)){
            throw new BusinessException('数据不存在');
        }
        // 有子级不能删除
        $hasChildren = Dept::where('parent_id',$id)->count();
        if($hasChildren > 0){
            throw new BusinessException('存在子级，不能删除');
        }
        $result = Dept::where('id','=',$id)->delete();
        return $result;
    }



}
